package main

import (
	"fmt"
	"gitee.com/frank2020/joy4/av"
	"gitee.com/frank2020/joy4/codec/h264parser"
	"gitee.com/frank2020/joy4/format"
	"gitee.com/frank2020/joy4/format/flv"
	"github.com/pion/rtp"
	"github.com/pion/rtp/codecs"
	"net"
	"os"
	"time"
)

func init() {
	format.RegisterAll()
}

func main() {

	file, err := os.Open("/Users/frank/workspace/gitee/joy4/format/flv/1.flv")
	if err != nil {
		fmt.Println(err)
		return
	}

	demuxer := flv.NewDemuxer(file)
	if err != nil {
		fmt.Println(err)
		return
	}

	streams, err := demuxer.Streams()
	if err != nil {
		fmt.Println(err)
		return
	}

	// rtp 发送
	conn, err := net.Dial("udp", "127.0.0.1:1234")
	defer conn.Close()
	if err != nil {
		os.Exit(1)
	}

	packetizer := rtp.NewPacketizer(1200, 96, 1111, &codecs.H264Payloader{}, rtp.NewRandomSequencer(), 90000)

	// 流信息
	for _, stream := range streams {
		if stream.Type().IsAudio() {
			astream := stream.(av.AudioCodecData)
			fmt.Println(astream.Type(), astream.SampleRate(), astream.SampleFormat(), astream.ChannelLayout())
		} else if stream.Type().IsVideo() {
			vstream := stream.(av.VideoCodecData)
			fmt.Println(vstream.Type(), vstream.Width(), vstream.Height())

			codec := vstream.(h264parser.CodecData)
			fmt.Println("sps : %s", codec.SPS())
			fmt.Println("pps : %s", codec.PPS())

			rtps := packetizer.Packetize(codec.SPS(), 90000/25)
			for _, rtp := range rtps {
				data, err := rtp.Marshal()
				if err != nil {
					fmt.Println(err)
				}
				conn.Write(data)
				fmt.Printf("%s \n", rtp.String())
			}

			rtps = packetizer.Packetize(codec.PPS(), 90000/25)
			for _, rtp := range rtps {
				data, err := rtp.Marshal()
				if err != nil {
					fmt.Println(err)
				}
				conn.Write(data)
				fmt.Printf("%s \n", rtp.String())
			}

		}
	}

	pkt, err := demuxer.ReadPacket()
	for err == nil {
		if streams[pkt.Idx].Type().IsVideo() {
			rtps := packetizer.Packetize(pkt.Data, 90000/25)
			for _, rtp := range rtps {
				data, err := rtp.Marshal()
				if err != nil {
					fmt.Println(err)
				}
				conn.Write(data)
				fmt.Printf("%s \n", rtp.String())
			}
		}
		pkt, err = demuxer.ReadPacket()
		time.Sleep(40 * time.Millisecond)
	}

}
